package com.superm.controller;

import com.superm.entity.Emp;
import com.superm.entity.SmbmsRuntimeException;
import com.superm.service.EmpService;
import com.superm.service.impl.EmpServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(path="/Login")
public class LoginPage {
    @Autowired
    private EmpService empService;
    //跳转登录页面
    @GetMapping(path = "/ConLogin")
    public String index(){
        return "LoginPage";
    }
    //认证失败后要执行的代码
    @PostMapping(path = "/ConLogin")
    public Map<String,Object> ConLogin(HttpServletRequest request){
        //获取错误信息
        Object obj = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        //判断错误类型
        if (obj.equals(UnknownAccountException.class.getName())){
            throw new SmbmsRuntimeException("账号错误","1001");
        }else if(obj.equals(IncorrectCredentialsException.class.getName())){
            throw new SmbmsRuntimeException("密码错误","1002");
        }
        return null;
    }
    //登录成功跳转的页面
    @RequestMapping(path = "/success")
    public String Success(HttpSession session){
        //获取认证主体
        Subject subjet = SecurityUtils.getSubject();
        //从认证主体取出认证信息
        Emp emp = (Emp)subjet.getPrincipal();
        //查询账号是否被封禁,如果封禁抛出异常
        emp = empService.selectIdUser(emp);
        System.out.println(emp);
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        if (emp.geteState().equals("禁用")){
            throw new SmbmsRuntimeException("该账号已被禁用","1003");
        }else {
            //放入session
            session.setAttribute("user",emp);
            return "index";
        }
    }
    /**
     * 局部处理异常
     * @return
     */
    @ExceptionHandler({RuntimeException.class})
    public ModelAndView exceptionHandler(Exception e, HttpServletRequest reuqest){
        if (e instanceof SmbmsRuntimeException){
            //向下转型
            SmbmsRuntimeException smbms = (SmbmsRuntimeException)e;
            reuqest.setAttribute("error",smbms.getErrMsg());
        }
        return new ModelAndView("LoginPage");
    }
}
